import { AfterViewInit, Component, OnDestroy, OnInit, Renderer2, ViewChild } from '@angular/core';
import { ConfigModule } from 'src/app/config.module';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { ValidatorService } from '../../../../../common/validator.service';
import { DragDrop } from '@angular/cdk/drag-drop';
import { JobService } from '../../service/job.service';

@Component({
    selector: 'app-run-option',
    templateUrl: './index.html',
    styleUrls: ['./index.scss'],
})
export class RunOptionComponent implements OnInit, AfterViewInit, OnDestroy {
    @ViewChild('modalContent') modalContent: any;
    @ViewChild('modalFooter') modalFooter: any;
    saveLoadingState: boolean;
    entity: any = {} as any;
    modalRef: NzModalRef; //用户操作弹窗
    taskName: string = '';
    constructor(
        public _config: ConfigModule,
        private _formBuilder: FormBuilder,
        private _router: Router,
        private _nzModalService: NzModalService,
        private _validService: ValidatorService,
        private _renderer2: Renderer2,
        private _dragDrop: DragDrop,
        private mainService: JobService,
    ) {
    }

    ngOnInit() {
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
    }


    /**
     * 操作弹窗
     */
    onModalOpen(jobId: number,jobGroup: string,taskName:string) {
        this.entity.jobId = jobId;
        this.entity.jobGroup = jobGroup;
        this.taskName = taskName;
        this.modalRef = this._nzModalService.create({
            nzTitle: '系统提示',
            nzContent: this.modalContent,
            nzFooter: this.modalFooter,
            nzWidth: "400px",
            nzBodyStyle: this._config.modalContentHeight,
        });

        this.modalRef.afterOpen.subscribe(() => {
            const modalDragRef = this._renderer2.selectRootElement('.ant-modal-content', true);
            const modalDragHeaderRef = this._renderer2.selectRootElement('.ant-modal-header', true);

            const modalDrag = this._dragDrop.createDrag(modalDragRef);
            modalDrag.withHandles([modalDragHeaderRef]);
            modalDrag.withBoundaryElement(document.body);
        });

        this.modalRef.afterClose.subscribe(() => {
            for (const key of Object.keys(this.entity)) {
                delete this.entity[key];
            }
            this.taskName = "";
        });
    }


    /**
     * 保存
     */
    onSave() {
        this.saveLoadingState = true;
        this.mainService.run(this.entity).subscribe((res) => {
            if (res.success) {
                this.modalRef.close();
            }
        }).add(()=>{
            this.saveLoadingState = false;
        });
    }

}
